<!-- 联盟产品库 -->
<template>
  <div>
    <div v-if="pageType === 'page'" class="p-4 pb-0 text-xl"
      >产品库已有<span class="text-color-[#2878ff]">{{ total }}</span
      >件商品</div
    >
    <BasicTable row-key="id" @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'productName'">
          <div class="flex flex-auto">
            <div class="flex-shrink-0">
              <Image
                :src="record.imageUrl"
                :width="pageType === 'page' ? '67px' : '40px'"
                :height="pageType === 'page' ? '67px' : '40px'"
                style="object-fit: cover"
              ></Image>
            </div>
            <div class="ml-3 text-left flex flex-col justify-between">
              <Tooltip :title="record.productName">
                <div class="line-clamp-2 max-h-12 w-[180px]" style="white-space: normal">
                  {{ record.productName }}
                </div>
              </Tooltip>
              <div>
                <Tag v-if="record.productDeleted">已删除</Tag>
                <Tag v-else-if="record.opPublishStatus == OPpublishStatus.NotPublished">被下架</Tag>
                <Tag v-else-if="record.publishStatus == PublishStatus.NotPublished">已下架</Tag>
              </div>
            </div>
          </div>
        </template>

        <template v-else-if="column.key === 'minPrice'">
          <Price
            :min-price="record.minPrice"
            :max-price="record.productMinPrice"
            :price-show-type="record.priceShowType"
          />
        </template>
        <template v-else-if="column.key === 'shopName'">
          <div class="flex items-center">
            <Avatar :src="record.shopLogo" class="flex-shrink-0" />
            <div class="ml-2">{{ record.shopName }}</div>
          </div>
        </template>
        <template v-else-if="column.key === 'userName'">
          <div class="flex items-center">
            <Avatar :src="record.userAvatar" class="flex-shrink-0" />
            <div class="ml-2">
              <span>{{ record.userName }}</span>
              <span>{{ record.userPhone }}</span>
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'memberName'">
          <div v-if="record.memberName" class="flex items-center">
            <Avatar :src="record.memberLogo" class="flex-shrink-0" />
            <div class="ml-2">
              <span>{{ record.memberName }}</span>
              <span>{{ record.levelName }}</span>
            </div>
          </div>
          <div v-else class="flex items-center">
            <Avatar :src="record.shopLogo" class="flex-shrink-0" />
            <div class="ml-2">{{ record.shopName }}</div>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '详情',
                onClick: () => openDetailModal(1, record),
              },
              {
                label: '移除',
                onClick: () => openRemoveProductModal(record),
              },
              {
                label: '推广设置',
                onClick: () => {
                  router.push(`/hby/resourceLeague/promotionSet?id=${record.id}`);
                },
              },
            ]"
          ></TableAction>
        </template>

        <template v-if="column.key === 'logisticsMode'">
          <span>{{
            dictionary.logisticsMode.find((v) => v.dictValue === record.logisticsMode)?.dictLabel
          }}</span>
        </template>
      </template>
    </BasicTable>
    <ProductLibDetail @register="registerDetail" @reload="reload"></ProductLibDetail>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema } from '@/components/Table';
  import { getProductCategory } from '@/api/hby/productManage/index';
  import Dictionary from '@/utils/dictionary';
  import { Image, Avatar, Tooltip, Modal, Tag } from 'ant-design-vue';
  import { useModal } from '@/components/Modal';
  import { formatMoney } from '@/utils/number';
  import dictionary from '@/utils/dictionary/localDicts';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';
  import {
    getProductList,
    removeProduct,
    getMerchantTemplateNoChoiceProductList,
  } from '@/api/hby/resourceLeague/index';
  import { ProductItem } from '@/api/hby/resourceLeague/type';
  import ProductLibDetail from '@/views/hby/productManage/ProductLib/ProductLibDetail.vue';
  import { cloneDeep } from 'lodash-es';
  import { OPpublishStatus, PublishStatus } from '@/enums/productManage';
  import { productCategoryList } from '@/api/hby/categoryManagement';
  import { isArray } from '@/utils/is';
  import Price from '@/components/Price/index.vue';
  const props = defineProps({
    pageType: {
      type: String,
      validator: (v: string) => ['page', 'modal'].includes(v),
      default: 'page',
    },
    groupId: { type: Number },
  });
  const emit = defineEmits(['selectionChange']);

  const { createMessage } = useMessage();
  const router = useRouter();

  const dicts = Dictionary.getLocalMulti(['productType']);

  const tableSchemas = reactive<FormSchema[]>([
    {
      field: `keyWord`,
      label: `搜索产品`,
      component: 'Input',
      componentProps: {
        placeholder: '输入商品名称/组织名称/发布者名称',
      },
      colProps: {
        span: 8,
      },
    },
    {
      field: `productCategoryId`,
      label: `产品分类`,
      component: 'ApiCascader',
      componentProps: {
        api: productCategoryList,
        isLoadData: false,
        initFetchParams: { size: 999 },
        labelField: 'name',
        valueField: 'id',
        isLeaf: (record) => {
          return !record.children;
        },
        showLastLabel: true,
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
      },
      colProps: {
        span: 6,
      },
    },
    {
      field: `productType`,
      label: `产品类型`,
      component: 'Select',
      componentProps: {
        fieldNames: { label: 'dictLabel', value: 'dictValue' },
        options: dicts.productType,
      },
      colProps: {
        span: 4,
      },
    },
  ]);

  const total = ref(0);
  const [registerTable, { reload, clearSelectedRowKeys, getRawDataSource }] = useTable({
    api: (params) => {
      clearSelectedRowKeys();
      if (isArray(params.productCategoryId)) {
        params.productCategoryId = params.productCategoryId[params.productCategoryId.length - 1];
      }
      return props.groupId
        ? getMerchantTemplateNoChoiceProductList({ id: props.groupId, ...params })
        : getProductList(params);
    },
    columns: [
      {
        title: '产品信息',
        dataIndex: 'productName',
        width: 272,
        align: 'center',
      },
      {
        title: '价格',
        dataIndex: 'minPrice',
        width: 180,
        align: 'center',
      },
      {
        title: '产品类型',
        dataIndex: 'productType',
        width: 120,
        align: 'center',
      },
      {
        title: '产品类目',
        dataIndex: 'productCategoryName',
        width: 150,
        align: 'center',
      },
      {
        title: '库存',
        dataIndex: 'totalStockNum',
        width: 150,
        align: 'center',
      },
      {
        title: '产品来源',
        dataIndex: 'shopName',
        width: 240,
        align: 'center',
      },
      {
        title: '发布者',
        dataIndex: 'userName',
        width: 214,
        align: 'center',
      },
      {
        title: '推入时间',
        dataIndex: 'createTime',
        width: 200,
        align: 'center',
      },
    ],
    showIndexColumn: props.pageType === 'page',
    clickToRowSelect: false,
    useSearchForm: true,
    showTableSetting: props.pageType === 'page',
    tableSetting: { fullScreen: true },
    formConfig: {
      labelWidth: 100,
      schemas: tableSchemas as unknown as FormSchema[],
    },
    actionColumn:
      props.pageType === 'page'
        ? {
            width: 200,
            title: '操作',
            dataIndex: 'action',
          }
        : undefined,
    rowSelection: {
      fixed: true,
      onChange: (selectedRowKeys, selectedRows) => {
        emit('selectionChange', selectedRows);
      },
    },
    afterFetch: (data: ProductItem[]) => {
      total.value = getRawDataSource().total;
      return data.map((item) => {
        return {
          ...item,
          productType: dicts.productType.find((v) => v.dictValue == item.productType)?.dictLabel,
        };
      });
    },
  });

  // 详情弹窗
  const [registerDetail, { openModal: openDetail }] = useModal();
  function openDetailModal(type: number, row: ProductItem) {
    let rowItem = cloneDeep(row);
    rowItem.id = rowItem.productId;
    openDetail(true, { type, row: rowItem });
  }

  // 移除产品弹窗
  function openRemoveProductModal(row: ProductItem) {
    Modal.confirm({
      title: '移除产品',
      content:
        '确定要将产品移除联盟产品库吗？移除后，其他通过联盟推广的产品链接都将失效，已产生订单不受影响。',
      cancelText: '暂不移除',
      okText: '确定移除',
      onOk: async () => {
        return new Promise<void>((resolve, reject) => {
          removeProduct(row.id)
            .then(() => {
              createMessage.success('移除成功！');
              resolve();
              reload();
            })
            .catch((err) => {
              reject(err);
            });
        });
      },
    });
  }
</script>

<style lang="less" scoped></style>
